package com.ruoyi.common.utils.mail;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


@Component
@Slf4j
public class EmailUtils {

    @Autowired
    private JavaMailSender javaMailSender;


    private String senderMailAddress;

    //默认
    public boolean sendMail(Map<String, Object> valueMap){
        return sendMail(valueMap,"default");
    }

    /**
     * 加载 thymeleaf 模板
     * @param valueMap
     * @param thymeleaf
     * @return
     */
    public boolean sendMail(Map<String, Object> valueMap,String thymeleaf){
        String htmlFilePath=thymeleaf+".html";
        File file=new File(htmlFilePath);
        String htmlContent="";
        if(file.exists()){//文件存在
            htmlContent = FileUtil.readString(file, Charset.forName("UTF-8"));
        }else{
            //没有内容
            htmlContent = valueMap.get("content")==null?"":valueMap.get("content").toString();
        }

        String title=toTranStringByObject(valueMap.get("title"));

        for(Map.Entry<String,Object> entry:valueMap.entrySet()){
            String key=entry.getKey();
            String value= toTranStringByObject(entry.getValue());
            htmlContent=htmlContent.replace("${"+key+"}",value);
            title=title.replace("${"+key+"}",value);
        }

        valueMap.put("title",title);

        valueMap.put("text",htmlContent);
        Object to=valueMap.get("to");
        if(to instanceof String){
            String toString=toTranStringByObject(to);
            valueMap.put("to",toString.split(";"));
        }
        Object cc=valueMap.get("cc");
        if(cc instanceof String){
            String ccString=toTranStringByObject(cc);
            valueMap.put("cc",ccString.split(";"));
        }
        Object bcc=valueMap.get("bcc");
        if(bcc instanceof String){
            String bccString= toTranStringByObject(bcc);
            valueMap.put("bcc",bccString.split(";"));
        }
        return sendSimpleMail(valueMap);
    }

    public  String toTranStringByObject(Object object){
        if(object==null)return "";
        return object.toString().trim();
    }


    public boolean sendSimpleMail(Map<String, Object> valueMap){
        MimeMessage mimeMessage = null;
        try {
            mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            // 设置发件人邮箱
//            helper.setFrom(senderMailAddress);
             helper.setFrom("ykyl@yikongenomics.com");
            // 设置收件人邮箱
            helper.setTo((String[])valueMap.get("to"));
            // 设置抄送人邮箱
            if(valueMap.get("cc")!=null){
                helper.setCc((String[])valueMap.get("cc"));
            }
            // 设置密送人邮箱
            if(valueMap.get("bcc")!=null){
                helper.setBcc((String[])valueMap.get("bcc"));
            }

            // 设置邮件标题
            helper.setSubject(valueMap.get("title").toString());

            helper.setText(valueMap.get("text").toString(),true);

            // 创建多重消息
            Multipart multipart = new MimeMultipart();
            boolean isSendFile =false;
            // 添加附件
            /**
             * 三种方式
             *  1. file = 文件对象File 或者 文件路径 - 单个文件
             *  2. fileList = 文件对象File - 多个文件 List<File> / File[]
             *  3. filePathList = 文件路径 - 多个文件 List<String> / String[]
             */
            if (valueMap.get("file") != null) {
                Object object = valueMap.get("file");
                if(object instanceof File){
                    File file = (File) object;
                    String fileName = file.getName();
                    FileSystemResource fileSystemResource = new FileSystemResource(file);
                    helper.addAttachment(fileName, fileSystemResource);

                    setFile(multipart,file.getAbsolutePath());
                    isSendFile = true;
                    setFile(multipart,fileName);
                }else{
                    String filePath = (String) object;
                    File file = new File(filePath);
                    String fileName = file.getName();
                    FileSystemResource fileSystemResource = new FileSystemResource(file);
                    helper.addAttachment(fileName, fileSystemResource);

                    setFile(multipart,filePath);
                    isSendFile = true;
                    setFile(multipart,fileName);
                }
            }

            if (valueMap.get("fileList") != null) {
                Object object = valueMap.get("fileList");
                if(object instanceof ArrayList){
                    List<File> fileList = (ArrayList) object;
                    for(File file: fileList) {
                        String fileName = file.getName();
                        FileSystemResource fileSystemResource = new FileSystemResource(file);
                        helper.addAttachment(fileName, fileSystemResource);

                        setFile(multipart,file.getAbsolutePath());
                        isSendFile = true;
                        setFile(multipart,fileName);
                    }
                }else{
                    File[] fileList = (File[])object;
                    for(File file: fileList) {
                        String fileName = file.getName();
                        FileSystemResource fileSystemResource = new FileSystemResource(file);
                        helper.addAttachment(fileName, fileSystemResource);
                        setFile(multipart,file.getAbsolutePath());
                        isSendFile = true;
                        setFile(multipart,fileName);
                    }
                }
            }
            if (valueMap.get("filePathList") != null) {
                Object object = valueMap.get("filePathList");
                if(object instanceof ArrayList){
                    List<String> filePathList = (ArrayList) object;
                    for(String filePath: filePathList) {
                        File file=new File(filePath);
                        String fileName = file.getName();
                        FileSystemResource fileSystemResource = new FileSystemResource(file);
                        helper.addAttachment(fileName, fileSystemResource);
                        setFile(multipart,filePath);
                        isSendFile = true;
                        setFile(multipart,fileName);
                    }
                }else{
                    String[] filePathList = (String[])object;
                    for(String filePath: filePathList) {
                        File file=new File(filePath);
                        String fileName = file.getName();
                        FileSystemResource fileSystemResource = new FileSystemResource(file);
                        helper.addAttachment(fileName, fileSystemResource);
                        setFile(multipart,filePath);
                        isSendFile = true;
                        setFile(multipart,fileName);
                    }
                }
            }

            if(isSendFile){
                // 发送完整消息
                BodyPart messageBodyPart = new MimeBodyPart();
//                messageBodyPart.setContent(valueMap.get("text").toString(),"text/plain");
                messageBodyPart.setContent(valueMap.get("text").toString(),"text/html;charset=utf-8");
                multipart.addBodyPart(messageBodyPart);
                mimeMessage.setContent(multipart);
            }
            // 发送邮件
            javaMailSender.send(mimeMessage);

        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public Multipart setFile(Multipart multipart, String filePath) throws MessagingException {
        // 附件部分
        // 创建消息部分
        BodyPart messageBodyPart = new MimeBodyPart();
        // 设置要发送附件的文件路径
        DataSource source = new FileDataSource(filePath);
        messageBodyPart.setDataHandler(new DataHandler(source));
        // messageBodyPart.setFileName(filename);
        // 处理附件名称中文（附带文件路径）乱码问题
        messageBodyPart.setFileName(source.getName());
        multipart.addBodyPart(messageBodyPart);
        return multipart;
    }

}
